<template>
  <div class="app">
    <transition name="sidebar">
      <Sidebar v-if="sidebarFlag" :newSession="handleNewSession" :foldSidebar="handleFoldSidebar" />
    </transition>


    <main class="main-content">

      <transition name="sidebar">
        <div v-if="!sidebarFlag" class="left-header">
          <button @click="handleNewSession" class="operate-btn new-session-btn" title="新建会话">
            <img src="../../assets/newSess.svg" alt="" style="width: 22px; " />
          </button>
          <button @click="handleFoldSidebar" class="operate-btn fold-btn" title="折叠">
            <img src="../../assets/fold.svg" alt="" style="width: 22px;" />
          </button>
        </div>
      </transition>

      <div v-if="newSession" class="welcome">
        <h1>Hi, 张三</h1>
      </div>

      <div id="sessionId" v-else class="main-session">
        <div v-for="(item, index) in sessionChats" :key="index" class="session-div">
          <div v-if="item.sessionType == 'chat'" class="chat-session">
            <span class="message-span">{{ item.session }}</span>

            <span class="typing-dots" v-if="sendFlag">
              <span class="dot"></span>
              <span class="dot"></span>
              <span class="dot"></span>
            </span>

            <div class="action-buttons">
              <button class="action-btn copy-btn">
                <img src="../../assets/copy.svg" @click="copyMessage(item, index)" alt="" style="width: 16px; " />
              </button>

              <button class="action-btn copy-btn">
                <img src="../../assets/like.svg" alt="" style="width: 16px; " />
              </button>
              <button class="action-btn copy-btn">
                <img src="../../assets/tread.svg" alt="" style="width: 16px; " />
              </button>
            </div>
          </div>
          <div v-else class="user-session">
            <div class="user-span">
              <!-- <input v-if="item.rewriteFlag" v-model="rewriteInput" class="rewrite-input" /> -->
              <div v-if="item.rewriteFlag" class="input-bar">
                <input v-model="rewriteInput" class="input-field" placeholder="请输入内容..." />
                <div class="button-group">
                  <button @click="cancelMessage(item, index)" class="cancel-btn">取消</button>
                  <button @click="finishMessage(item, index)" class="send-btn">发送</button>
                </div>
              </div>


              <span class="message-span" v-else>{{ item.session }}</span>
            </div>
            <div class="action-buttons" style="justify-content: flex-end;">
              <button v-if="!rewriteFlag" class="action-btn copy-btn">
                <img src="../../assets/copy.svg" @click="copyMessage(item, index)" alt="" style="width: 16px; " />
              </button>
              <button v-if="!rewriteFlag" class="action-btn copy-btn">
                <img src="../../assets/edit.svg" @click="rewriteMessage(item, index)" alt=""
                  style="width: 16px; color: #8a8a8a;" />
              </button>
              <!-- <button v-if="rewriteFlag" class="action-btn copy-btn">
                <img src="../../assets/wrong.svg" @click="cancelMessage(item, index)" alt=""
                  style="width: 16px; color: #8a8a8a;" />
              </button>
              <button v-if="rewriteFlag" class="action-btn copy-btn">
                <img src="../../assets/right.svg" @click="finishMessage(item, index)" alt=""
                  style="width: 16px; color: #8a8a8a;" />
              </button> -->
            </div>
          </div>
        </div>
      </div>

      <div class="bottom-div">
        <div class="function-buttons">
          <ButtonCard title="检索相似图片" desc="在库中查找相似图片" />
          <ButtonCard title="企业规范" desc="快速定位企业规范文件" />
          <ButtonCard title="学习资料" desc="指导软件使用及设计" />
          <ButtonCard title="企业问答" desc="总结企业库中数据" />
        </div>

        <InputBox ref="inputBoxRef" v-model:newSession="newSession" :sendMessage="sendMessage"
          :createEmptyMessage="createEmptyMessage" :updateMessageContent="updateMessageContent"
          v-model:sendFlag="sendFlag" />
      </div>

    </main>
  </div>
</template>

<script setup>
import Sidebar from '../../components/Sidebar.vue'
import ButtonCard from '../../components/ButtonCard.vue'
import InputBox from '../../components/InputBox.vue'
import { v4 as uuidv4 } from "uuid";
import { ref, watch } from 'vue';

const inputBoxRef = ref(null);

// 组件注册  Sidebar, ButtonCard, InputBox
const newSession = ref(true); // 是否进行对话
const sidebarFlag = ref(true);
const sendFlag = ref(false);
const rewriteFlag = ref(false);
const rewriteInput = ref(''); // 重写输入框内容
const sessionChats = ref([
  // { session: '欢迎来到ChatGPT', sessionType: 'chat' },
  // { session: '请输入你的问题', sessionType: 'user' },
]); // 聊天会话列表

watch(sessionChats, (newVal) => {
  // 每次 sessionChats 变化后，滚动到底部
  const targetDiv = document.getElementById('sessionId');

  if (targetDiv) {
    // 平滑滚动到底部
    targetDiv.scrollTo({
      top: targetDiv.scrollHeight,
      behavior: 'smooth'
    });
  }
}, { deep: true });

const sendMessage = (session, sessionType) => {
  if (sessionType == 'chat') {
    // 模拟延时  一点一点往出蹦
    for (let i = 0; i < session.length; i++) {
      setTimeout(() => {
        if (i === 0) {
          sessionChats.value.push({ session: '', sessionType });
        } else {
          sessionChats.value.pop();
          sessionChats.value.push({ session: session.slice(0, i + 1), sessionType });
        }
      }, i * 50); // 每个字符间隔50毫秒
    }
  } else {
    sessionChats.value.push({ session, sessionType });

  }

};

const handleNewSession = () => {
  newSession.value = true;
  sessionChats.value = [];
};

const handleFoldSidebar = () => {
  sidebarFlag.value = !sidebarFlag.value;
};

const updateStreamMessage = (content, type) => {
  // 更新最后一条消息的内容
  if (sessionChats.value.length > 0) {
    const lastMessage = sessionChats.value[sessionChats.value.length - 1];
    if (lastMessage.type === type) {
      lastMessage.content = content;
    }
  }
};

const createEmptyMessage = (type) => {
  const newMessage = {
    id: Date.now(),
    sessionType: type,
    session: '',
    timestamp: new Date()
  };

  sessionChats.value.push(newMessage);
  return newMessage.id;
};

const updateMessageContent = (id, content) => {
  const message = sessionChats.value.find(msg => msg.id === id);
  if (message) {
    message.session = content;

  }
};

const copyMessage = (item, index) => {
  navigator.clipboard.writeText(item.session).then(() => {
    console.log('文本已复制到剪贴板');
  }).catch(err => {
    console.error('无法复制文本: ', err);
  });
};

const rewriteMessage = (item, index) => {
  rewriteFlag.value = true;
  item.rewriteFlag = true;
  rewriteInput.value = item.session;
};

const cancelMessage = (item, index) => {
  item.rewriteFlag = false;
  rewriteFlag.value = false;
  rewriteInput.value = '';
};

const finishMessage = (item, index) => {
  inputBoxRef.value.handleSend(rewriteInput.value);

  rewriteFlag.value = false;
  item.rewriteFlag = false;
  rewriteInput.value = '';
};
</script>

<style scoped lang="scss">
.app {
  display: flex;
  height: 100vh;
  background-color: #f3f3f3;
  font-family: 'Segoe UI', sans-serif;
  width: 100%;
}

.main-content {
  flex: 1;
  width: 100vh;
  padding: 20px;
  overflow-y: auto;

  display: flex;
  justify-content: space-between;
  flex-direction: column;
  background-color: #ffffff;
  // 圆角
  border-radius: 10px;
}


.welcome {
  text-align: center;
  margin-top: 25%;
  font-size: 1.5rem;
  color: #000;
}

.function-buttons {
  display: flex;
  gap: 16px;
  /* 卡片间距 */
  justify-content: flex-start;
  /* 左对齐 */
  align-items: stretch;
  /* 等高 */
  flex-wrap: nowrap;
  /* 不换行 */
  overflow-x: auto;
  /* 如果内容过多可以横向滚动 */
  padding: 8px 0;
}

/* 如果 ButtonCard 组件需要样式 */
.function-buttons>* {
  flex: 1;
  /* 等分宽度 */
  min-width: 200px;
  /* 最小宽度 */
}

/* @media (max-width: 1000px) {
  .function-buttons {
    flex-direction: column;
    align-items: center;
  }
} */




.main-session {
  // background-color: #ebebeb;
  height: calc(100%);
  overflow-y: auto;
  padding: 10px;
  border-radius: 10px;

  .session-div {
    display: block;

    .chat-session {
      float: left;
      max-width: 70%;
      // background-color: #fafafa;

      border-top-left-radius: 10px;
      /* 设置左上角弧度为10px */
      border-bottom-left-radius: 0;
      /* 设置左下角弧度为10px */
      border-top-right-radius: 10px;
      /* 设置右上角弧度为10px */
      border-bottom-right-radius: 10px;
      /* 设置右下角弧度为0，即保持直角 */
      padding-top: 6px;
      padding-bottom: 6px;
      padding-left: 10px;
      padding-right: 10px;
      margin: 10px;
      clear: both;
      display: flex;
      text-align: left;

      justify-content: space-between;
      flex-direction: column;

      position: relative;

      /* 添加这行，清除左右浮动，强制换行 */
      span {
        color: #000;
      }


    }

    .user-session {
      float: right;
      max-width: 70%;


      margin: 10px;
      clear: both;

      justify-content: space-between;
      flex-direction: column;

      position: relative;

      /* 添加这行，清除左右浮动，强制换行 */
      span {
        color: #000;
      }

      .user-span {
        background-color: #edf3fe;
        border-top-left-radius: 10px;
        /* 设置左上角弧度为10px */
        border-bottom-left-radius: 10px;
        /* 设置左下角弧度为10px */
        border-top-right-radius: 10px;
        /* 设置右上角弧度为10px */
        border-bottom-right-radius: 0;
        /* 设置右下角弧度为0，即保持直角 */
        padding-top: 6px;
        padding-bottom: 6px;
        padding-left: 10px;
        padding-right: 10px;
      }
    }
  }

}

.bottom-div {
  height: 35%;
}

.action-buttons {
  display: none;
  gap: 8px;
  justify-content: flex-start;
  margin-top: 8px;
}

.action-btn {
  padding: 4px 8px;
  border: 0px solid #ddd;
  border-radius: 6px;
  background-color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background-color: #f5f5f5;
  }
}

.copy-btn:hover {
  border-color: #0078d4;
  color: #0078d4;
}


.left-header {
  margin-bottom: 20px;
  /* 让按钮组靠右对齐，更符合视觉习惯 */
  display: flex;
  justify-content: flex-start;
  gap: 8px; // 按钮之间的间距，避免拥挤
  position: sticky;
}

// 优化按钮样式：统一尺寸、增强hover效果、增加点击反馈
.operate-btn {
  width: 36px; // 固定宽度，让两个按钮大小一致
  height: 36px; // 固定高度，保持圆形视觉
  border: none; // 去掉默认边框
  border-radius: 50%; // 圆形按钮，更精致
  font-size: 16px; // 图标放大，更醒目
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.12);
  }

  &:active {
    transform: scale(0.98);
  }
}

.new-session-btn {
  color: #ef4444;

  &:hover {
    background-color: #fef2f2;
  }
}

.fold-btn {
  color: #f59e0b;

  &:hover {
    background-color: #fffbeb;
  }
}

/* 侧边栏进入和离开的过渡效果 */
.sidebar-enter-active,
.sidebar-leave-active {
  transition: all 0.3s ease;
}

.sidebar-enter-from {
  transform: translateX(-100%);
  opacity: 0;
}

.sidebar-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}

.typing-dots {
  display: inline-flex;
}

.dot {
  width: 4px;
  height: 4px;
  background: currentColor;
  border-radius: 50%;
  margin: 0 1px;
  animation: dot-bounce 1.4s infinite ease-in-out;
}

.dot:nth-child(1) {
  animation-delay: -0.32s;
}

.dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes dot-bounce {

  0%,
  80%,
  100% {
    transform: scale(0.8);
    opacity: 0.5;
  }

  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-session:hover .action-buttons {
  display: flex;
  /* 鼠标悬停时显示 */
}

.user-session:hover .action-buttons {
  display: flex;
  /* 鼠标悬停时显示 */
}

/* 核心：美化输入框样式 */
.rewrite-input {
  /* 基础样式 */
  padding: 8px 12px;
  /* 内边距，避免文字贴边 */
  border: 1px solid #e5e7eb;
  /* 浅灰色边框，适配大多数UI */
  border-radius: 6px;
  /* 圆角，柔和不尖锐 */
  font-size: 14px;
  /* 字体大小，与周边文字协调 */
  color: #1f2937;
  /* 文字颜色，清晰不刺眼 */
  width: 280px;
  /* 固定宽度，也可设为 100% 自适应 */
  box-sizing: border-box;
  /* 确保 padding 和 border 不撑大宽度 */

  /* 交互效果：聚焦时高亮 */
  outline: none;
  /* 清除默认聚焦边框 */
  transition: all 0.2s ease;
  /* 过渡动画，体验更丝滑 */
}

.input-bar {
  display: flex;
  align-items: center;
  border: 1px solid #4f9bff;
  /* 蓝色边框，匹配示例风格 */
  border-radius: 20px;
  /* 大圆角，视觉柔和 */
  padding: 0 12px;
  /* 左右内边距，避免内容贴边 */
  background-color: #edf3fe;

  /* 深灰背景，匹配示例色调 */
  border: none;
  outline: none;
  resize: none;
}

/* 输入框：占满剩余空间，样式简洁 */
.input-field {
  flex: 1;
  /* 占满容器剩余宽度 */
  height: 40px;
  /* 固定高度，视觉统一 */
  border: none;
  /* 清除默认边框 */
  outline: none;
  /* 清除聚焦边框 */
  background: transparent;
  /* 透明背景，继承父容器 */
  color: #101317;
  /* 浅灰文字，提升可读性 */
  font-size: 14px;
  /* 字体大小，匹配示例 */
}

/* 按钮组：横向排列，控制按钮布局 */
.button-group {
  display: flex;
  gap: 8px;
  /* 按钮之间的间距 */
}

/* 取消按钮：灰色文字，无背景 */
.cancel-btn {
  border: none;
  background: transparent;
  color: #a0aec0;
  /* 浅灰文字，与示例一致 */
  font-size: 14px;
  cursor: pointer;
}

/* 发送按钮：蓝色背景，白色文字，圆角 */
.send-btn {
  border: none;
  border-radius: 16px;
  /* 小圆角，与外层大圆角呼应 */
  background-color: #2563eb;
  /* 深蓝色，匹配示例发送按钮 */
  color: #ffffff;
  font-size: 14px;
  padding: 6px 16px;
  /* 内边距，控制按钮大小 */
  cursor: pointer;
}
</style>
